package com.example.slidingui;

import java.util.Stack;
import android.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.SlidingDrawer;
import android.widget.SlidingDrawer.OnDrawerCloseListener;
import android.widget.SlidingDrawer.OnDrawerOpenListener;
import android.widget.SlidingDrawer.OnDrawerScrollListener;

public class MainActivity extends FragmentActivity implements OnDrawerCloseListener, OnDrawerOpenListener, OnDrawerScrollListener {
	static final String TAG = "SlidingUiActivity";
	SlidingDrawer mSliding;
	Stack<Fragment> mFragments = new Stack<Fragment>();
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_sliding_ui);

		mSliding = (SlidingDrawer) findViewById(R.id.sliding);
		mSliding.setOnDrawerCloseListener(this);
		mSliding.setOnDrawerOpenListener(this);

		Bundle args = new Bundle();
		args.putInt("action", -999);

		ContentFragment f = new ContentFragment();
		f.setArguments(args);
		addFragment(f);
		
		mSliding.open();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	public void clearFragments() {
		for (Fragment f : mFragments) {
			getFragmentManager().beginTransaction().detach(f);
		}
	}

	public void addFragmentWithStack(Fragment f, String stack) {
		mFragments.add(f);
		final int container = mSliding.getHandle().getId();
		getFragmentManager().beginTransaction().replace(container, f).addToBackStack(null).commitAllowingStateLoss();
		mSliding.open();

	}

	public void addFragment(Fragment f) {
		final int container = mSliding.getHandle().getId();
		getFragmentManager().beginTransaction().replace(container, f).addToBackStack(null).commitAllowingStateLoss();
		mSliding.open();
	}

	public void toggleMenu() {
		// Log.d(TAG, "toggleMenu()");
		mSliding.toggle();
	}

	@Override
	public void onBackPressed() {
		if (mSliding.isOpened()) {
			super.onBackPressed();
		} else {
			mSliding.open();
		}
	}

	@Override
	public void onScrollStarted() {
		// Log.d(TAG, "onScrollStarted()");
		mSliding.lock();
	}
	@Override
	public void onScrollEnded() {
		// Log.d(TAG, "onScrollEnded()");
		// if (mSliding.isOpened()) {
		// mSliding.lock();
		// } else {
		// mSliding.unlock();
		// }
	}
	@Override
	public void onDrawerOpened() {
		// Log.d(TAG, "onDrawerOpened()");
		mSliding.lock();
	}
	@Override
	public void onDrawerClosed() {
		// Log.d(TAG, "onDrawerClosed()");
		mSliding.unlock();
	}
}
